Calculus in `SymPy`
Link
Calculus - SymPy 1.12 documentation
Setting Up SymPy
Before diving into calculus operations, initialize SymPy
with symbols and functions:
from sympy import symbols, diff, integrate, limit, series, sin, exp, ln
# Define symbols
x, y, z = symbols('x y z')
Differentiation
Differentiate functions symbolically:
# Differentiate f(x) = x^2
f_prime = diff(x**2, x) # Returns 2*x
# Partial differentiation of f(x, y) = x^2 + xy
partial_f_x = diff(x**2 + x*y, x) # Returns 2*x + y
partial_f_y = diff(x**2 + x*y, y) # Returns x
Integration
Perform both definite and indefinite integrations:
# Indefinite integration of f(x) = x^2
integral_f = integrate(x**2, x) # Returns x**3/3
# Definite integration of f(x) = x^2 from 0 to 1
definite_integral_f = integrate(x**2, (x, 0, 1)) # Returns 1/3
Limits
Compute the limit of functions as a variable approaches a value:
# Limit of sin(x)/x as x -> 0
lim_sin_x = limit(sin(x)/x, x, 0) # Returns 1
# Limit of (1+1/x)^x as x -> infinity
lim_exp = limit((1+1/x)**x, x, sympy.oo) # Returns E
Series Expansion
Expand functions into their Taylor series around a point:
# Expand exp(x) around 0 up to 5th order
series_exp = series(exp(x), x, 0, 5)
# Returns 1 + x + x**2/2 + x**3/6 + x**4/24 + O(x**5)
# Series expansion of ln(1+x) around 0
series_ln = series(ln(1+x), x, 0, 4)
# Returns x - x**2/2 + x**3/3 - x**4/4 + O(x**5)
Solving Differential Equations
SymPy
can also solve differential equations symbolically. Here's a basic example:
from sympy import Function, dsolve, Eq, Derivative
# Define an unknown function and differential equation
f = Function('f')
diffeq = Eq(Derivative(f(x), x, x) - 2*Derivative(f(x), x) + f(x), sin(x))
# Solve the differential equation
sol = dsolve(diffeq, f(x))